<template>
  <div>
    <!--面包屑模块-->
    <el-breadcrumb separator-class="el-icon-arrow-right" style="padding: 10px">
      <el-breadcrumb-item :to="{ path: '/manage/' + this.teacherId }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>班级管理</el-breadcrumb-item>
      <el-breadcrumb-item>我的班级</el-breadcrumb-item>
      <el-breadcrumb-item>班级学生</el-breadcrumb-item>
    </el-breadcrumb>
    <!--卡片视图区域-->
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>{{ currentClass.className }} - 学生列表</span>
        <el-button style="float: right; padding: 3px 0" type="text" @click="addStudentDialogVisible = true">添加学生</el-button>
        <el-button style="float: right; padding: 3px 0; margin-right: 20px" type="text" @click="batchAddStudentDialogVisible = true">批量添加学生</el-button>
      </div>
      <!-- 搜索区域 -->
      <el-row :gutter="20" style="margin-bottom: 20px">
        <el-col :span="6">
          <el-input placeholder="请输入学生姓名或学号查询" v-model="queryInfo.query" clearable @clear="getStudentList">
            <el-button slot="append" icon="el-icon-search" @click="getStudentList"></el-button>
          </el-input>
        </el-col>
        <el-col :span="3">
          <el-button type="primary" @click="exportStudentList">导出学生名单</el-button>
        </el-col>
        <el-col :span="3">
          <el-button type="success" @click="returnToClassList">返回班级列表</el-button>
        </el-col>
      </el-row>
      <!-- 学生列表 -->
      <el-table :data="studentList" border stripe>
        <el-table-column type="index" label="#" width="50"></el-table-column>
        <el-table-column prop="studentID" label="学号" width="150"></el-table-column>
        <el-table-column prop="name" label="姓名" width="120"></el-table-column>
        <el-table-column prop="gender" label="性别" width="80"></el-table-column>
        <el-table-column prop="phone" label="联系电话" width="150"></el-table-column>
        <el-table-column prop="notes" label="备注" width="180"></el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button size="mini" type="primary" @click="editStudent(scope.row)">编辑</el-button>
            <el-button size="mini" type="danger" @click="removeStudentFromClass(scope.row)">移出班级</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页区域 -->
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="queryInfo.pageNum" :page-sizes="[5, 10, 15, 20]" :page-size="queryInfo.pageSize" layout="total, sizes, prev, pager, next, jumper" :total="total" style="margin-top: 15px">
      </el-pagination>
    </el-card>
    <!-- 添加学生对话框 -->
    <el-dialog title="添加学生" :visible.sync="addStudentDialogVisible" width="40%" @close="addStudentDialogClosed">
      <el-form :model="addStudentForm" :rules="studentFormRules" ref="addStudentFormRef" label-width="100px">
        <el-form-item label="学号" prop="studentID">
          <el-autocomplete
            v-model="addStudentForm.studentID"
            :fetch-suggestions="queryStudentIdAsync"
            placeholder="请输入学生学号"
            :trigger-on-focus="false"
            @select="handleStudentIdSelect"
          ></el-autocomplete>
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input v-model="addStudentForm.name"></el-input>
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-select v-model="addStudentForm.gender" placeholder="请选择性别">
            <el-option label="男" value="男"></el-option>
            <el-option label="女" value="女"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="联系电话" prop="phone">
          <el-input v-model="addStudentForm.phone"></el-input>
        </el-form-item>
        <el-form-item label="备注" prop="notes">
          <el-input v-model="addStudentForm.notes"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addStudentDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitAddStudentForm">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 批量添加学生对话框 -->
    <el-dialog title="批量添加学生" :visible.sync="batchAddStudentDialogVisible" width="40%" @close="batchAddStudentDialogClosed">
      <el-form label-width="100px">
        <el-form-item label="Excel文件">
          <el-upload class="upload-demo" :action="uploadUrl" :headers="headers" :on-success="handleUploadSuccess" :on-error="handleUploadError" :before-upload="beforeUpload" accept=".xlsx,.xls" :limit="1" :file-list="fileList">
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传Excel文件，且不超过10MB</div>
          </el-upload>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="downloadTemplate">下载模板</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <!-- 编辑学生对话框 -->
    <el-dialog title="编辑学生信息" :visible.sync="editStudentDialogVisible" width="40%" @close="editStudentDialogClosed">
      <el-form :model="editStudentForm" :rules="studentFormRules" ref="editStudentFormRef" label-width="100px">
        <el-form-item label="学号" prop="studentID">
          <el-input v-model="editStudentForm.studentID" readonly></el-input>
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input v-model="editStudentForm.name"></el-input>
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-select v-model="editStudentForm.gender" placeholder="请选择性别">
            <el-option label="男" value="男"></el-option>
            <el-option label="女" value="女"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="联系电话" prop="phone">
          <el-input v-model="editStudentForm.phone"></el-input>
        </el-form-item>
        <!-- <el-form-item label="备注" prop="notes">
          <el-input v-model="editStudentForm.notes"></el-input>
        </el-form-item> -->
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editStudentDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitEditStudentForm">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'ClassStudents',
  data() {
    return {
      teacherId: sessionStorage.getItem('userID'),
      // 当前班级信息
      currentClass: JSON.parse(sessionStorage.getItem('currentClass') || '{}'),
      // 查询参数
      queryInfo: {
        query: '',
        pageNum: 1,
        pageSize: 10,
        classId: ''
      },
      // 总数据条数
      total: 0,
      // 学生列表
      studentList: [],
      // 添加学生对话框
      addStudentDialogVisible: false,
      addStudentForm: {
        studentID: '',
        name: '',
        gender: '',
        phone: '',
        notes: '',
        classId: ''
      },
      // 批量添加学生对话框
      batchAddStudentDialogVisible: false,
      fileList: [],
      uploadUrl: this.$http + '/student/batchImport',
      headers: {
        'Content-Type': 'multipart/form-data'
      },
      // 编辑学生对话框
      editStudentDialogVisible: false,
      editStudentForm: {
        studentID: '',
        name: '',
        gender: '',
        phone: '',
        notes: '',
        classId: ''
      },
      // 表单验证规则
      studentFormRules: {
        studentID: [
          { required: true, message: '请输入学号', trigger: 'blur' },
          { pattern: /^[0-9]{11}$/, message: '学号必须是11位数字', trigger: 'blur' }
        ],
        name: [
          { required: true, message: '请输入姓名', trigger: 'blur' },
          { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' }
        ],
        gender: [
          { required: true, message: '请选择性别', trigger: 'change' }
        ],
        phone: [
          { required: true, message: '请输入联系电话', trigger: 'blur' },
          { pattern: /1(3[0-9]|4[01456879]|5[0-35-9]|6[2567]|7[0-8]|8[0-9]|9[0-35-9])\d{8}/, message: '请输入正确形式的手机号', trigger: 'blur' }
        ]
      }
    }
  },
  created () {
    // 确保有班级信息
    if (!this.currentClass.classId) {
      this.$message.error('未选择班级')
      this.$router.push('/manage/' + this.teacherId + '/class')
      return
    }
    
    // 设置查询参数
    this.queryInfo.classId = this.currentClass.classId
    // 获取学生列表
    this.getStudentList()
  },
  methods: {
    // 获取学生列表
    async getStudentList () {
      try {
        console.log('获取班级学生列表，参数:', {
          classId: this.queryInfo.classId,
          pageNum: this.queryInfo.pageNum,
          pageSize: this.queryInfo.pageSize,
          query: this.queryInfo.query.trim() || undefined
        })
        
        const params = {
          classId: this.queryInfo.classId,
          pageNum: this.queryInfo.pageNum,
          pageSize: this.queryInfo.pageSize
        }
        
        // 如果有查询条件
        if (this.queryInfo.query.trim() !== '') {
          params.query = this.queryInfo.query.trim()
        }
        
        const { data: res } = await this.$http.get('/class/students', { params })
        console.log('班级学生列表响应:', res)
        
        if (res.code === 200) {
          this.studentList = res.data.list || res.data || []
          this.total = res.data.total || (Array.isArray(res.data) ? res.data.length : 0)
          console.log('设置学生列表:', this.studentList)
          console.log('设置总数:', this.total)
        } else {
          this.$message.error(res.message || '获取学生列表失败')
          console.error('获取学生列表失败，错误信息:', res.message)
        }
      } catch (error) {
        console.error('获取学生列表失败', error)
        this.$message.error('获取学生列表失败')
      }
    },
    
    // 每页显示条数改变
    handleSizeChange (newSize) {
      this.queryInfo.pageSize = newSize
      this.getStudentList()
    },
    
    // 当前页改变
    handleCurrentChange (newPage) {
      this.queryInfo.pageNum = newPage
      this.getStudentList()
    },
    
    // 返回班级列表
    returnToClassList () {
      this.$router.push('/manage/' + this.teacherId + '/class')
    },
    
    // 导出学生名单
    async exportStudentList () {
      try {
        // 发起导出请求
        const { data: res } = await this.$http.get('/student/export', {
          params: { classId: this.currentClass.classId },
          responseType: 'blob'
        })
        
        // 创建下载链接
        const blob = new Blob([res], { type: 'application/vnd.ms-excel' })
        const link = document.createElement('a')
        link.href = window.URL.createObjectURL(blob)
        link.download = `${this.currentClass.className}学生名单.xlsx`
        link.click()
        
        this.$message.success('导出成功')
      } catch (error) {
        console.error('导出学生名单失败', error)
        this.$message.error('导出学生名单失败')
      }
    },
    
    // 添加学生对话框关闭
    addStudentDialogClosed () {
      this.$refs.addStudentFormRef.resetFields()
    },
    
    // 提交添加学生表单
    submitAddStudentForm () {
      this.$refs.addStudentFormRef.validate(async valid => {
        if (!valid) return
        
        // 设置班级ID
        this.addStudentForm.classId = this.currentClass.classId
        
        try {
          const { data: res } = await this.$http.post('/student/add', this.addStudentForm)
          
          if (res.code === 200) {
            this.$message.success('添加学生成功')
            this.addStudentDialogVisible = false
            this.getStudentList()
          } else {
            this.$message.error(res.message || '添加学生失败')
          }
        } catch (error) {
          console.error('添加学生失败', error)
          this.$message.error('添加学生失败')
        }
      })
    },
    
    // 编辑学生
    editStudent (row) {
      this.editStudentForm = JSON.parse(JSON.stringify(row))
      this.editStudentDialogVisible = true
    },
    
    // 编辑学生对话框关闭
    editStudentDialogClosed () {
      this.$refs.editStudentFormRef.resetFields()
    },
    
    // 提交编辑学生表单
    submitEditStudentForm () {
      this.$refs.editStudentFormRef.validate(async valid => {
        if (!valid) return
        
        try {
          const { data: res } = await this.$http.put('/student/update', this.editStudentForm)
          
          if (res.code === 200) {
            this.$message.success('更新学生成功')
            this.editStudentDialogVisible = false
            this.getStudentList()
          } else {
            this.$message.error(res.message || '更新学生失败')
          }
        } catch (error) {
          console.error('更新学生失败', error)
          this.$message.error('更新学生失败')
        }
      })
    },
    
    // 移出学生
    async removeStudentFromClass (row) {
      try {
        // 确认删除
        const confirmResult = await this.$confirm(
          `确定要将学生"${row.name}"从班级"${this.currentClass.className}"中移出吗？`,
          '提示',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        ).catch(err => err)
        
        // 如果用户点击取消，则返回
        if (confirmResult !== 'confirm') {
          return this.$message.info('已取消操作')
        }
        
        // 发送请求
        const { data: res } = await this.$http.put('/student/updateClass', {
          studentID: row.studentID,
          classId: null
        })
        
        if (res.code === 200) {
          this.$message.success('已将学生移出班级')
          this.getStudentList()
        } else {
          this.$message.error(res.message || '操作失败')
        }
      } catch (error) {
        console.error('移出学生失败', error)
        this.$message.error('移出学生失败')
      }
    },
    
    // 批量添加学生对话框关闭
    batchAddStudentDialogClosed () {
      this.fileList = []
    },
    
    // 上传前检查
    beforeUpload (file) {
      const isExcel = file.type === 'application/vnd.ms-excel' || 
                       file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
      const isLt10M = file.size / 1024 / 1024 < 10
      
      if (!isExcel) {
        this.$message.error('上传文件只能是Excel文件')
        return false
      }
      
      if (!isLt10M) {
        this.$message.error('上传文件大小不能超过10MB')
        return false
      }
      
      return true
    },
    
    // 上传成功处理
    handleUploadSuccess (response, file, fileList) {
      if (response.code === 200) {
        this.$message.success('批量导入学生成功')
        this.batchAddStudentDialogVisible = false
        this.getStudentList()
      } else {
        this.$message.error(response.message || '批量导入学生失败')
      }
    },
    
    // 上传失败处理
    handleUploadError (error, file, fileList) {
      console.error('上传文件失败', error)
      this.$message.error('上传文件失败')
    },
    
    // 下载模板
    async downloadTemplate () {
      try {
        const { data: res } = await this.$http.get('/student/downloadTemplate', {
          responseType: 'blob'
        })
        
        // 创建下载链接
        const blob = new Blob([res], { type: 'application/vnd.ms-excel' })
        const link = document.createElement('a')
        link.href = window.URL.createObjectURL(blob)
        link.download = '学生导入模板.xlsx'
        link.click()
        
        this.$message.success('模板下载成功')
      } catch (error) {
        console.error('下载模板失败', error)
        this.$message.error('下载模板失败')
      }
    },
    
    // 学号自动完成
    async queryStudentIdAsync (queryString, cb) {
      if (queryString.trim() === '') {
        cb([])
        return
      }
      
      try {
        const { data: res } = await this.$http.get('/student/searchByStudentIdPrefix', {
          params: { prefix: queryString }
        })
        
        if (res.code === 200) {
          const studentList = res.data || []
          const suggestions = studentList.map(student => ({
            value: student.studentID,
            student: student,
            label: `${student.studentID} - ${student.name || ''}`
          }))
          cb(suggestions)
        } else {
          cb([])
        }
      } catch (error) {
        console.error('获取学生列表失败', error)
        cb([])
      }
    },
    
    // 学号选中事件
    handleStudentIdSelect (item) {
      if (item && item.student) {
        this.addStudentForm.studentID = item.value
        this.addStudentForm.name = item.student.name || ''
        this.addStudentForm.gender = item.student.gender || '男'
        this.addStudentForm.phone = item.student.phone || ''
        this.addStudentForm.notes = item.student.notes || ''
      }
    }
  }
}
</script>

<style scoped>
.box-card {
  margin-bottom: 20px;
}
.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}
.clearfix:after {
  clear: both;
}
.el-upload__tip {
  line-height: 1.2;
  color: #909399;
  font-size: 12px;
}
</style>
